<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Go语言操作MySQL | 小狐档案库</title>
    <meta name="generator" content="VuePress 1.8.2">
    <link rel="icon" href="/favicon.ico">
    <meta name="description" content="学习资料">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.0c36f186.css" as="style"><link rel="preload" href="/assets/js/app.7029ddab.js" as="script"><link rel="preload" href="/assets/js/3.ebaa3085.js" as="script"><link rel="preload" href="/assets/js/1.8ce67e8c.js" as="script"><link rel="preload" href="/assets/js/40.56bda9a8.js" as="script"><link rel="prefetch" href="/assets/js/10.15c1f9c8.js"><link rel="prefetch" href="/assets/js/11.dc2fbddf.js"><link rel="prefetch" href="/assets/js/12.26ab1f36.js"><link rel="prefetch" href="/assets/js/13.6e1d4dbc.js"><link rel="prefetch" href="/assets/js/14.0cd48e80.js"><link rel="prefetch" href="/assets/js/15.74a9f029.js"><link rel="prefetch" href="/assets/js/16.24ef3382.js"><link rel="prefetch" href="/assets/js/17.c8a9bd0f.js"><link rel="prefetch" href="/assets/js/18.fbd494c2.js"><link rel="prefetch" href="/assets/js/19.f9a0df71.js"><link rel="prefetch" href="/assets/js/20.e6d0df38.js"><link rel="prefetch" href="/assets/js/21.932645cc.js"><link rel="prefetch" href="/assets/js/22.d6027dce.js"><link rel="prefetch" href="/assets/js/23.53bce141.js"><link rel="prefetch" href="/assets/js/24.ed3b8b64.js"><link rel="prefetch" href="/assets/js/25.ed88877e.js"><link rel="prefetch" href="/assets/js/26.f5ad24d5.js"><link rel="prefetch" href="/assets/js/27.64ad45b4.js"><link rel="prefetch" href="/assets/js/28.f308f8ab.js"><link rel="prefetch" href="/assets/js/29.4d95742d.js"><link rel="prefetch" href="/assets/js/30.0a867de0.js"><link rel="prefetch" href="/assets/js/31.f12def86.js"><link rel="prefetch" href="/assets/js/32.6b4fd8b7.js"><link rel="prefetch" href="/assets/js/33.4bb2aa9c.js"><link rel="prefetch" href="/assets/js/34.013e731c.js"><link rel="prefetch" href="/assets/js/35.6b263ef8.js"><link rel="prefetch" href="/assets/js/36.06acf3cc.js"><link rel="prefetch" href="/assets/js/37.fe72c29c.js"><link rel="prefetch" href="/assets/js/38.9b4e0bd6.js"><link rel="prefetch" href="/assets/js/39.0cde0408.js"><link rel="prefetch" href="/assets/js/4.9b5650bb.js"><link rel="prefetch" href="/assets/js/41.007ae34c.js"><link rel="prefetch" href="/assets/js/42.bdaf414b.js"><link rel="prefetch" href="/assets/js/43.78d32d4e.js"><link rel="prefetch" href="/assets/js/44.a10cf8a5.js"><link rel="prefetch" href="/assets/js/45.19e14721.js"><link rel="prefetch" href="/assets/js/46.57ebcf06.js"><link rel="prefetch" href="/assets/js/47.9a513ffe.js"><link rel="prefetch" href="/assets/js/48.245b165a.js"><link rel="prefetch" href="/assets/js/49.fab43655.js"><link rel="prefetch" href="/assets/js/5.a16ef7f8.js"><link rel="prefetch" href="/assets/js/50.48c191fd.js"><link rel="prefetch" href="/assets/js/51.28a94b0e.js"><link rel="prefetch" href="/assets/js/52.e783fbf9.js"><link rel="prefetch" href="/assets/js/53.2f0e960e.js"><link rel="prefetch" href="/assets/js/54.577ff54e.js"><link rel="prefetch" href="/assets/js/55.4bb99598.js"><link rel="prefetch" href="/assets/js/56.e820e954.js"><link rel="prefetch" href="/assets/js/57.0cea0cfa.js"><link rel="prefetch" href="/assets/js/58.e31cfcd0.js"><link rel="prefetch" href="/assets/js/59.458ab168.js"><link rel="prefetch" href="/assets/js/6.7da424ba.js"><link rel="prefetch" href="/assets/js/60.e9caace2.js"><link rel="prefetch" href="/assets/js/61.0b61afdb.js"><link rel="prefetch" href="/assets/js/62.c240acab.js"><link rel="prefetch" href="/assets/js/63.71cd2a97.js"><link rel="prefetch" href="/assets/js/64.977ea29b.js"><link rel="prefetch" href="/assets/js/65.79b2d62a.js"><link rel="prefetch" href="/assets/js/66.8da69071.js"><link rel="prefetch" href="/assets/js/67.fdc57d7e.js"><link rel="prefetch" href="/assets/js/68.d43eabe9.js"><link rel="prefetch" href="/assets/js/7.6e92edd1.js"><link rel="prefetch" href="/assets/js/8.2389170b.js"><link rel="prefetch" href="/assets/js/9.77841f24.js">
    <link rel="stylesheet" href="/assets/css/0.styles.0c36f186.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container" data-v-1156296a><div data-v-1156296a><div id="loader-wrapper" class="loading-wrapper" data-v-d48f4d20 data-v-1156296a data-v-1156296a><div class="loader-main" data-v-d48f4d20><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div><div data-v-d48f4d20></div></div> <!----> <!----></div> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-4e82dffc data-v-1156296a data-v-1156296a><h3 class="title" data-v-4e82dffc data-v-4e82dffc>小狐档案库</h3> <p class="description" data-v-4e82dffc data-v-4e82dffc>学习资料</p> <label id="box" class="inputBox" data-v-4e82dffc data-v-4e82dffc><input type="password" value="" data-v-4e82dffc> <span data-v-4e82dffc>Konck! Knock!</span> <button data-v-4e82dffc>OK</button></label> <div class="footer" data-v-4e82dffc data-v-4e82dffc><span data-v-4e82dffc><i class="iconfont reco-theme" data-v-4e82dffc></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4e82dffc>vuePress-theme-reco</a></span> <span data-v-4e82dffc><i class="iconfont reco-copyright" data-v-4e82dffc></i> <a data-v-4e82dffc><span data-v-4e82dffc>小狐</span>
            
          <span data-v-4e82dffc>2021-9-1 - </span>
          2021
        </a></span></div></div> <div class="hide" data-v-1156296a><header class="navbar" data-v-1156296a><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="小狐档案库" class="logo"> <span class="site-name">小狐档案库</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/GO/" class="nav-link"><i class="undefined"></i>
  GO
</a></li><li class="dropdown-item"><!----> <a href="/categories/面试系列/" class="nav-link"><i class="undefined"></i>
  面试系列
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tag
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  足迹
</a></div><div class="nav-item"><a href="https://www.xiaohu.team" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-message"></i>
  摇光图库
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-1156296a></div> <aside class="sidebar" data-v-1156296a><div class="personal-info-wrapper" data-v-828910c6 data-v-1156296a><img src="/avatar.jpg" alt="author-avatar" class="personal-img" data-v-828910c6> <h3 class="name" data-v-828910c6>
    小狐
  </h3> <div class="num" data-v-828910c6><div data-v-828910c6><h3 data-v-828910c6>58</h3> <h6 data-v-828910c6>Articles</h6></div> <div data-v-828910c6><h3 data-v-828910c6>20</h3> <h6 data-v-828910c6>Tags</h6></div></div> <ul class="social-links" data-v-828910c6></ul> <hr data-v-828910c6></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  首页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      分类
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/GO/" class="nav-link"><i class="undefined"></i>
  GO
</a></li><li class="dropdown-item"><!----> <a href="/categories/面试系列/" class="nav-link"><i class="undefined"></i>
  面试系列
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tag
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  足迹
</a></div><div class="nav-item"><a href="https://www.xiaohu.team" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-message"></i>
  摇光图库
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav> <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>go语言学习</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>go语言基础学习</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gin</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading open"><span>数据库操作</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/blogs/GO/go_mysql/go_mysql.html" aria-current="page" class="active sidebar-link">Go语言操作MySQL</a></li><li><a href="/blogs/GO/go_mysql/go_sqlx.html" class="sidebar-link">sqlx库使用指南</a></li><li><a href="/blogs/GO/go_mysql/go_sqlx_2.html" class="sidebar-link">GO使用sqlx批量插入数据的若干方法</a></li></ul></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gorm</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>gorm</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>NoSql</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>消息队列</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><p class="sidebar-heading"><span>go三方库</span> <span class="arrow right"></span></p> <!----></section></li></ul></section></li></ul> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-4e82dffc data-v-1156296a><h3 class="title" data-v-4e82dffc data-v-4e82dffc>Go语言操作MySQL</h3> <!----> <label id="box" class="inputBox" data-v-4e82dffc data-v-4e82dffc><input type="password" value="" data-v-4e82dffc> <span data-v-4e82dffc>Konck! Knock!</span> <button data-v-4e82dffc>OK</button></label> <div class="footer" data-v-4e82dffc data-v-4e82dffc><span data-v-4e82dffc><i class="iconfont reco-theme" data-v-4e82dffc></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4e82dffc>vuePress-theme-reco</a></span> <span data-v-4e82dffc><i class="iconfont reco-copyright" data-v-4e82dffc></i> <a data-v-4e82dffc><span data-v-4e82dffc>小狐</span>
            
          <span data-v-4e82dffc>2021-9-1 - </span>
          2021
        </a></span></div></div> <div data-v-1156296a><main class="page"><section><div class="page-title"><h1 class="title">Go语言操作MySQL</h1> <div data-v-1ff7123e><i class="iconfont reco-account" data-v-1ff7123e><span data-v-1ff7123e>小狐</span></i> <i class="iconfont reco-date" data-v-1ff7123e><span data-v-1ff7123e>9/10/2021</span></i> <!----> <i class="tags iconfont reco-tag" data-v-1ff7123e><span class="tag-item" data-v-1ff7123e>GO</span><span class="tag-item" data-v-1ff7123e>数据库操作</span><span class="tag-item" data-v-1ff7123e>MySQL</span></i></div></div> <div class="theme-reco-content content__default"><h1 id="go语言操作mysql"><a href="#go语言操作mysql" class="header-anchor">#</a> Go语言操作MySQL</h1> <p>MySQL是业界常用的关系型数据库，本文介绍了Go语言如何操作MySQL数据库。</p> <h1 id="go操作mysql"><a href="#go操作mysql" class="header-anchor">#</a> Go操作MySQL</h1> <h2 id="连接"><a href="#连接" class="header-anchor">#</a> 连接</h2> <p>Go语言中的<code>database/sql</code>包提供了保证SQL或类SQL数据库的泛用接口，并不提供具体的数据库驱动。使用<code>database/sql</code>包时必须注入（至少）一个数据库驱动。</p> <p>我们常用的数据库基本上都有完整的第三方实现。例如：<a href="https://github.com/go-sql-driver/mysql" target="_blank" rel="noopener noreferrer">MySQL驱动<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <h3 id="下载依赖"><a href="#下载依赖" class="header-anchor">#</a> 下载依赖</h3> <div class="language-bash line-numbers-mode"><pre class="language-bash"><code>go get -u github.com/go-sql-driver/mysql
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="使用mysql驱动"><a href="#使用mysql驱动" class="header-anchor">#</a> 使用MySQL驱动</h3> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">Open</span><span class="token punctuation">(</span>driverName<span class="token punctuation">,</span> dataSourceName <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token operator">*</span>DB<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>Open打开一个dirverName指定的数据库，dataSourceName指定数据源，一般至少包括数据库文件名和其它连接必要的信息。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;database/sql&quot;</span>

	<span class="token boolean">_</span> <span class="token string">&quot;github.com/go-sql-driver/mysql&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token comment">// DSN:Data Source Name</span>
	dsn <span class="token operator">:=</span> <span class="token string">&quot;user:password@tcp(127.0.0.1:3306)/dbname&quot;</span>
	db<span class="token punctuation">,</span> err <span class="token operator">:=</span> sql<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;mysql&quot;</span><span class="token punctuation">,</span> dsn<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> db<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment">// 注意这行代码要写在上面err判断的下面</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p><strong>思考题</strong>： 为什么上面代码中的<code>defer db.Close()</code>语句不应该写在<code>if err != nil</code>的前面呢？</p> <h3 id="初始化连接"><a href="#初始化连接" class="header-anchor">#</a> 初始化连接</h3> <p>Open函数可能只是验证其参数格式是否正确，实际上并不创建与数据库的连接。如果要检查数据源的名称是否真实有效，应该调用Ping方法。</p> <p>返回的DB对象可以安全地被多个goroutine并发使用，并且维护其自己的空闲连接池。因此，Open函数应该仅被调用一次，很少需要关闭这个DB对象。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 定义一个全局对象db</span>
<span class="token keyword">var</span> db <span class="token operator">*</span>sql<span class="token punctuation">.</span>DB

<span class="token comment">// 定义一个初始化数据库的函数</span>
<span class="token keyword">func</span> <span class="token function">initDB</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">// DSN:Data Source Name</span>
	dsn <span class="token operator">:=</span> <span class="token string">&quot;user:password@tcp(127.0.0.1:3306)/sql_test?charset=utf8mb4&amp;parseTime=True&quot;</span>
	<span class="token comment">// 不会校验账号密码是否正确</span>
	<span class="token comment">// 注意！！！这里不要使用:=，我们是给全局变量赋值，然后在main函数中使用全局变量db</span>
	db<span class="token punctuation">,</span> err <span class="token operator">=</span> sql<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">&quot;mysql&quot;</span><span class="token punctuation">,</span> dsn<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">}</span>
	<span class="token comment">// 尝试与数据库建立连接（校验dsn是否正确）</span>
	err <span class="token operator">=</span> db<span class="token punctuation">.</span><span class="token function">Ping</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> err
	<span class="token punctuation">}</span>
	<span class="token keyword">return</span> <span class="token boolean">nil</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	err <span class="token operator">:=</span> <span class="token function">initDB</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 调用输出化数据库的函数</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;init db failed,err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br></div></div><p>其中<code>sql.DB</code>是表示连接的数据库对象（结构体实例），它保存了连接数据库相关的所有信息。它内部维护着一个具有零到多个底层连接的连接池，它可以安全地被多个goroutine同时使用。</p> <h3 id="setmaxopenconns"><a href="#setmaxopenconns" class="header-anchor">#</a> SetMaxOpenConns</h3> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">SetMaxOpenConns</span><span class="token punctuation">(</span>n <span class="token builtin">int</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>SetMaxOpenConns</code>设置与数据库建立连接的最大数目。 如果n大于0且小于最大闲置连接数，会将最大闲置连接数减小到匹配最大开启连接数的限制。 如果n&lt;=0，不会限制最大开启连接数，默认为0（无限制）。</p> <h3 id="setmaxidleconns"><a href="#setmaxidleconns" class="header-anchor">#</a> SetMaxIdleConns</h3> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">SetMaxIdleConns</span><span class="token punctuation">(</span>n <span class="token builtin">int</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>SetMaxIdleConns设置连接池中的最大闲置连接数。 如果n大于最大开启连接数，则新的最大闲置连接数会减小到匹配最大开启连接数的限制。 如果n&lt;=0，不会保留闲置连接。</p> <h2 id="crud"><a href="#crud" class="header-anchor">#</a> CRUD</h2> <h3 id="建库建表"><a href="#建库建表" class="header-anchor">#</a> 建库建表</h3> <p>我们先在MySQL中创建一个名为<code>sql_test</code>的数据库</p> <div class="language-sql line-numbers-mode"><pre class="language-sql"><code><span class="token keyword">CREATE</span> <span class="token keyword">DATABASE</span> sql_test<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>进入该数据库:</p> <div class="language-sql line-numbers-mode"><pre class="language-sql"><code><span class="token keyword">use</span> sql_test<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>执行以下命令创建一张用于测试的数据表：</p> <div class="language-sql line-numbers-mode"><pre class="language-sql"><code><span class="token keyword">CREATE</span> <span class="token keyword">TABLE</span> <span class="token punctuation">`</span><span class="token keyword">user</span><span class="token punctuation">`</span> <span class="token punctuation">(</span>
    <span class="token punctuation">`</span>id<span class="token punctuation">`</span> <span class="token keyword">BIGINT</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token operator">NOT</span> <span class="token boolean">NULL</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>name<span class="token punctuation">`</span> <span class="token keyword">VARCHAR</span><span class="token punctuation">(</span><span class="token number">20</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token string">''</span><span class="token punctuation">,</span>
    <span class="token punctuation">`</span>age<span class="token punctuation">`</span> <span class="token keyword">INT</span><span class="token punctuation">(</span><span class="token number">11</span><span class="token punctuation">)</span> <span class="token keyword">DEFAULT</span> <span class="token string">'0'</span><span class="token punctuation">,</span>
    <span class="token keyword">PRIMARY</span> <span class="token keyword">KEY</span><span class="token punctuation">(</span><span class="token punctuation">`</span>id<span class="token punctuation">`</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span><span class="token keyword">ENGINE</span><span class="token operator">=</span><span class="token keyword">InnoDB</span> <span class="token keyword">AUTO_INCREMENT</span><span class="token operator">=</span><span class="token number">1</span> <span class="token keyword">DEFAULT</span> <span class="token keyword">CHARSET</span><span class="token operator">=</span>utf8mb4<span class="token punctuation">;</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><h3 id="查询"><a href="#查询" class="header-anchor">#</a> 查询</h3> <p>为了方便查询，我们事先定义好一个结构体来存储user表的数据。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">type</span> user <span class="token keyword">struct</span> <span class="token punctuation">{</span>
	id   <span class="token builtin">int</span>
	age  <span class="token builtin">int</span>
	name <span class="token builtin">string</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h4 id="单行查询"><a href="#单行查询" class="header-anchor">#</a> 单行查询</h4> <p>单行查询<code>db.QueryRow()</code>执行一次查询，并期望返回最多一行结果（即Row）。QueryRow总是返回非nil的值，直到返回值的Scan方法被调用时，才会返回被延迟的错误。（如：未找到结果）</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">QueryRow</span><span class="token punctuation">(</span>query <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">*</span>Row
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>具体示例代码：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 查询单条数据示例</span>
<span class="token keyword">func</span> <span class="token function">queryRowDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;select id, name, age from user where id=?&quot;</span>
	<span class="token keyword">var</span> u user
	<span class="token comment">// 非常重要：确保QueryRow之后调用Scan方法，否则持有的数据库链接不会被释放</span>
	err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">QueryRow</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;scan failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;id:%d name:%s age:%d\n&quot;</span><span class="token punctuation">,</span> u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><h4 id="多行查询"><a href="#多行查询" class="header-anchor">#</a> 多行查询</h4> <p>多行查询<code>db.Query()</code>执行一次查询，返回多行结果（即Rows），一般用于执行select命令。参数args表示query中的占位参数。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">Query</span><span class="token punctuation">(</span>query <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token operator">*</span>Rows<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>具体示例代码：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 查询多条数据示例</span>
<span class="token keyword">func</span> <span class="token function">queryMultiRowDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;select id, name, age from user where id &gt; ?&quot;</span>
	rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;query failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 非常重要：关闭rows释放持有的数据库链接</span>
	<span class="token keyword">defer</span> rows<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token comment">// 循环读取结果集中的数据</span>
	<span class="token keyword">for</span> rows<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">var</span> u user
		err <span class="token operator">:=</span> rows<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
		<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
			fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;scan failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
			<span class="token keyword">return</span>
		<span class="token punctuation">}</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;id:%d name:%s age:%d\n&quot;</span><span class="token punctuation">,</span> u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br></div></div><h3 id="插入数据"><a href="#插入数据" class="header-anchor">#</a> 插入数据</h3> <p>插入、更新和删除操作都使用<code>Exec</code>方法。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">Exec</span><span class="token punctuation">(</span>query <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>Result<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>Exec执行一次命令（包括查询、删除、更新、插入等），返回的Result是对已执行的SQL命令的总结。参数args表示query中的占位参数。</p> <p>具体插入数据示例代码如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 插入数据</span>
<span class="token keyword">func</span> <span class="token function">insertRowDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;insert into user(name, age) values (?,?)&quot;</span>
	ret<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token string">&quot;王五&quot;</span><span class="token punctuation">,</span> <span class="token number">38</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;insert failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	theID<span class="token punctuation">,</span> err <span class="token operator">:=</span> ret<span class="token punctuation">.</span><span class="token function">LastInsertId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 新插入数据的id</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;get lastinsert ID failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;insert success, the id is %d.\n&quot;</span><span class="token punctuation">,</span> theID<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><h3 id="更新数据"><a href="#更新数据" class="header-anchor">#</a> 更新数据</h3> <p>具体更新数据示例代码如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 更新数据</span>
<span class="token keyword">func</span> <span class="token function">updateRowDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;update user set age=? where id = ?&quot;</span>
	ret<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token number">39</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;update failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	n<span class="token punctuation">,</span> err <span class="token operator">:=</span> ret<span class="token punctuation">.</span><span class="token function">RowsAffected</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 操作影响的行数</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;get RowsAffected failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;update success, affected rows:%d\n&quot;</span><span class="token punctuation">,</span> n<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><h3 id="删除数据"><a href="#删除数据" class="header-anchor">#</a> 删除数据</h3> <p>具体删除数据的示例代码如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 删除数据</span>
<span class="token keyword">func</span> <span class="token function">deleteRowDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;delete from user where id = ?&quot;</span>
	ret<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;delete failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	n<span class="token punctuation">,</span> err <span class="token operator">:=</span> ret<span class="token punctuation">.</span><span class="token function">RowsAffected</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 操作影响的行数</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;get RowsAffected failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;delete success, affected rows:%d\n&quot;</span><span class="token punctuation">,</span> n<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><h2 id="mysql预处理"><a href="#mysql预处理" class="header-anchor">#</a> MySQL预处理</h2> <h3 id="什么是预处理"><a href="#什么是预处理" class="header-anchor">#</a> 什么是预处理？</h3> <p>普通SQL语句执行过程：</p> <ol><li>客户端对SQL语句进行占位符替换得到完整的SQL语句。</li> <li>客户端发送完整SQL语句到MySQL服务端</li> <li>MySQL服务端执行完整的SQL语句并将结果返回给客户端。</li></ol> <p>预处理执行过程：</p> <ol><li>把SQL语句分成两部分，命令部分与数据部分。</li> <li>先把命令部分发送给MySQL服务端，MySQL服务端进行SQL预处理。</li> <li>然后把数据部分发送给MySQL服务端，MySQL服务端对SQL语句进行占位符替换。</li> <li>MySQL服务端执行完整的SQL语句并将结果返回给客户端。</li></ol> <h3 id="为什么要预处理"><a href="#为什么要预处理" class="header-anchor">#</a> 为什么要预处理？</h3> <ol><li>优化MySQL服务器重复执行SQL的方法，可以提升服务器性能，提前让服务器编译，一次编译多次执行，节省后续编译的成本。</li> <li>避免SQL注入问题。</li></ol> <h3 id="go实现mysql预处理"><a href="#go实现mysql预处理" class="header-anchor">#</a> Go实现MySQL预处理</h3> <p><code>database/sql</code>中使用下面的<code>Prepare</code>方法来实现预处理操作。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">Prepare</span><span class="token punctuation">(</span>query <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token operator">*</span>Stmt<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><code>Prepare</code>方法会先将sql语句发送给MySQL服务端，返回一个准备好的状态用于之后的查询和命令。返回值可以同时执行多个查询和命令。</p> <p>查询操作的预处理示例代码如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 预处理查询示例</span>
<span class="token keyword">func</span> <span class="token function">prepareQueryDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;select id, name, age from user where id &gt; ?&quot;</span>
	stmt<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Prepare</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;prepare failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> stmt<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> stmt<span class="token punctuation">.</span><span class="token function">Query</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;query failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> rows<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token comment">// 循环读取结果集中的数据</span>
	<span class="token keyword">for</span> rows<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">var</span> u user
		err <span class="token operator">:=</span> rows<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
		<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
			fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;scan failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
			<span class="token keyword">return</span>
		<span class="token punctuation">}</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;id:%d name:%s age:%d\n&quot;</span><span class="token punctuation">,</span> u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br></div></div><p>插入、更新和删除操作的预处理十分类似，这里以插入操作的预处理为例：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 预处理插入示例</span>
<span class="token keyword">func</span> <span class="token function">prepareInsertDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> <span class="token string">&quot;insert into user(name, age) values (?,?)&quot;</span>
	stmt<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Prepare</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;prepare failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> stmt<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">=</span> stmt<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span><span class="token string">&quot;小王子&quot;</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;insert failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	<span class="token boolean">_</span><span class="token punctuation">,</span> err <span class="token operator">=</span> stmt<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span><span class="token string">&quot;沙河娜扎&quot;</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;insert failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;insert success.&quot;</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br></div></div><h3 id="sql注入问题"><a href="#sql注入问题" class="header-anchor">#</a> SQL注入问题</h3> <p><strong>我们任何时候都不应该自己拼接SQL语句！</strong></p> <p>这里我们演示一个自行拼接SQL语句的示例，编写一个根据name字段查询user表的函数如下：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// sql注入示例</span>
<span class="token keyword">func</span> <span class="token function">sqlInjectDemo</span><span class="token punctuation">(</span>name <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	sqlStr <span class="token operator">:=</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">&quot;select id, name, age from user where name='%s'&quot;</span><span class="token punctuation">,</span> name<span class="token punctuation">)</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;SQL:%s\n&quot;</span><span class="token punctuation">,</span> sqlStr<span class="token punctuation">)</span>
	<span class="token keyword">var</span> u user
	err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">QueryRow</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>u<span class="token punctuation">.</span>id<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>u<span class="token punctuation">.</span>age<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;exec failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;user:%#v\n&quot;</span><span class="token punctuation">,</span> u<span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>此时以下输入字符串都可以引发SQL注入问题：</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token function">sqlInjectDemo</span><span class="token punctuation">(</span><span class="token string">&quot;xxx' or 1=1#&quot;</span><span class="token punctuation">)</span>
<span class="token function">sqlInjectDemo</span><span class="token punctuation">(</span><span class="token string">&quot;xxx' union select * from user #&quot;</span><span class="token punctuation">)</span>
<span class="token function">sqlInjectDemo</span><span class="token punctuation">(</span><span class="token string">&quot;xxx' and (select count(*) from user) &lt;10 #&quot;</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>**补充：**不同的数据库中，SQL语句使用的占位符语法不尽相同。</p> <table><thead><tr><th style="text-align:center;">数据库</th> <th style="text-align:center;">占位符语法</th></tr></thead> <tbody><tr><td style="text-align:center;">MySQL</td> <td style="text-align:center;"><code>?</code></td></tr> <tr><td style="text-align:center;">PostgreSQL</td> <td style="text-align:center;"><code>$1</code>, <code>$2</code>等</td></tr> <tr><td style="text-align:center;">SQLite</td> <td style="text-align:center;"><code>?</code> 和<code>$1</code></td></tr> <tr><td style="text-align:center;">Oracle</td> <td style="text-align:center;"><code>:name</code></td></tr></tbody></table> <h2 id="go实现mysql事务"><a href="#go实现mysql事务" class="header-anchor">#</a> Go实现MySQL事务</h2> <h3 id="什么是事务"><a href="#什么是事务" class="header-anchor">#</a> 什么是事务？</h3> <p>事务：一个最小的不可再分的工作单元；通常一个事务对应一个完整的业务(例如银行账户转账业务，该业务就是一个最小的工作单元)，同时这个完整的业务需要执行多次的DML(insert、update、delete)语句共同联合完成。A转账给B，这里面就需要执行两次update操作。</p> <p>在MySQL中只有使用了<code>Innodb</code>数据库引擎的数据库或表才支持事务。事务处理可以用来维护数据库的完整性，保证成批的SQL语句要么全部执行，要么全部不执行。</p> <h3 id="事务的acid"><a href="#事务的acid" class="header-anchor">#</a> 事务的ACID</h3> <p>通常事务必须满足4个条件（ACID）：原子性（Atomicity，或称不可分割性）、一致性（Consistency）、隔离性（Isolation，又称独立性）、持久性（Durability）。</p> <table><thead><tr><th style="text-align:center;">条件</th> <th style="text-align:center;">解释</th></tr></thead> <tbody><tr><td style="text-align:center;">原子性</td> <td style="text-align:center;">一个事务（transaction）中的所有操作，要么全部完成，要么全部不完成，不会结束在中间某个环节。事务在执行过程中发生错误，会被回滚（Rollback）到事务开始前的状态，就像这个事务从来没有执行过一样。</td></tr> <tr><td style="text-align:center;">一致性</td> <td style="text-align:center;">在事务开始之前和事务结束以后，数据库的完整性没有被破坏。这表示写入的资料必须完全符合所有的预设规则，这包含资料的精确度、串联性以及后续数据库可以自发性地完成预定的工作。</td></tr> <tr><td style="text-align:center;">隔离性</td> <td style="text-align:center;">数据库允许多个并发事务同时对其数据进行读写和修改的能力，隔离性可以防止多个事务并发执行时由于交叉执行而导致数据的不一致。事务隔离分为不同级别，包括读未提交（Read uncommitted）、读提交（read committed）、可重复读（repeatable read）和串行化（Serializable）。</td></tr> <tr><td style="text-align:center;">持久性</td> <td style="text-align:center;">事务处理结束后，对数据的修改就是永久的，即便系统故障也不会丢失。</td></tr></tbody></table> <h3 id="事务相关方法"><a href="#事务相关方法" class="header-anchor">#</a> 事务相关方法</h3> <p>Go语言中使用以下三个方法实现MySQL中的事务操作。 开始事务</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>db <span class="token operator">*</span>DB<span class="token punctuation">)</span> <span class="token function">Begin</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token operator">*</span>Tx<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>提交事务</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>tx <span class="token operator">*</span>Tx<span class="token punctuation">)</span> <span class="token function">Commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p>回滚事务</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token punctuation">(</span>tx <span class="token operator">*</span>Tx<span class="token punctuation">)</span> <span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">error</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><h3 id="事务示例"><a href="#事务示例" class="header-anchor">#</a> 事务示例</h3> <p>下面的代码演示了一个简单的事务操作，该事物操作能够确保两次更新操作要么同时成功要么同时失败，不会存在中间状态。</p> <div class="language-go line-numbers-mode"><pre class="language-go"><code><span class="token comment">// 事务操作示例</span>
<span class="token keyword">func</span> <span class="token function">transactionDemo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	tx<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Begin</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 开启事务</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		<span class="token keyword">if</span> tx <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
			tx<span class="token punctuation">.</span><span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 回滚</span>
		<span class="token punctuation">}</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;begin trans failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	sqlStr1 <span class="token operator">:=</span> <span class="token string">&quot;Update user set age=30 where id=?&quot;</span>
	ret1<span class="token punctuation">,</span> err <span class="token operator">:=</span> tx<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span>sqlStr1<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		tx<span class="token punctuation">.</span><span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 回滚</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;exec sql1 failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	affRow1<span class="token punctuation">,</span> err <span class="token operator">:=</span> ret1<span class="token punctuation">.</span><span class="token function">RowsAffected</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		tx<span class="token punctuation">.</span><span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 回滚</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;exec ret1.RowsAffected() failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>

	sqlStr2 <span class="token operator">:=</span> <span class="token string">&quot;Update user set age=40 where id=?&quot;</span>
	ret2<span class="token punctuation">,</span> err <span class="token operator">:=</span> tx<span class="token punctuation">.</span><span class="token function">Exec</span><span class="token punctuation">(</span>sqlStr2<span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		tx<span class="token punctuation">.</span><span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 回滚</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;exec sql2 failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>
	affRow2<span class="token punctuation">,</span> err <span class="token operator">:=</span> ret2<span class="token punctuation">.</span><span class="token function">RowsAffected</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
		tx<span class="token punctuation">.</span><span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 回滚</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;exec ret1.RowsAffected() failed, err:%v\n&quot;</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
		<span class="token keyword">return</span>
	<span class="token punctuation">}</span>

	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>affRow1<span class="token punctuation">,</span> affRow2<span class="token punctuation">)</span>
	<span class="token keyword">if</span> affRow1 <span class="token operator">==</span> <span class="token number">1</span> <span class="token operator">&amp;&amp;</span> affRow2 <span class="token operator">==</span> <span class="token number">1</span> <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;事务提交啦...&quot;</span><span class="token punctuation">)</span>
		tx<span class="token punctuation">.</span><span class="token function">Commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 提交事务</span>
	<span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
		tx<span class="token punctuation">.</span><span class="token function">Rollback</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;事务回滚啦...&quot;</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>

	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">&quot;exec trans success!&quot;</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br></div></div></div></section> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">2021-9-2: </span> <span class="time">9/3/2021, 6:20:18 PM</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev"><a href="/blogs/GO/go_web/gin/gin_zip_used.html" class="prev">
            使用zap接收gin框架默认的日志并配置日志归档
          </a></span> <span class="next"><a href="/blogs/GO/go_mysql/go_sqlx.html">
            sqlx库使用指南
          </a></span></p></div> <div class="comments-wrapper"><!----></div> <ul class="side-bar sub-sidebar-wrapper" style="width:12rem;" data-v-70334359><li class="level-2" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#连接" class="sidebar-link reco-side-连接" data-v-70334359>连接</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#下载依赖" class="sidebar-link reco-side-下载依赖" data-v-70334359>下载依赖</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#使用mysql驱动" class="sidebar-link reco-side-使用mysql驱动" data-v-70334359>使用MySQL驱动</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#初始化连接" class="sidebar-link reco-side-初始化连接" data-v-70334359>初始化连接</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#setmaxopenconns" class="sidebar-link reco-side-setmaxopenconns" data-v-70334359>SetMaxOpenConns</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#setmaxidleconns" class="sidebar-link reco-side-setmaxidleconns" data-v-70334359>SetMaxIdleConns</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#crud" class="sidebar-link reco-side-crud" data-v-70334359>CRUD</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#建库建表" class="sidebar-link reco-side-建库建表" data-v-70334359>建库建表</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#查询" class="sidebar-link reco-side-查询" data-v-70334359>查询</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#插入数据" class="sidebar-link reco-side-插入数据" data-v-70334359>插入数据</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#更新数据" class="sidebar-link reco-side-更新数据" data-v-70334359>更新数据</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#删除数据" class="sidebar-link reco-side-删除数据" data-v-70334359>删除数据</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#mysql预处理" class="sidebar-link reco-side-mysql预处理" data-v-70334359>MySQL预处理</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#什么是预处理" class="sidebar-link reco-side-什么是预处理" data-v-70334359>什么是预处理？</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#为什么要预处理" class="sidebar-link reco-side-为什么要预处理" data-v-70334359>为什么要预处理？</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#go实现mysql预处理" class="sidebar-link reco-side-go实现mysql预处理" data-v-70334359>Go实现MySQL预处理</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#sql注入问题" class="sidebar-link reco-side-sql注入问题" data-v-70334359>SQL注入问题</a></li><li class="level-2" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#go实现mysql事务" class="sidebar-link reco-side-go实现mysql事务" data-v-70334359>Go实现MySQL事务</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#什么是事务" class="sidebar-link reco-side-什么是事务" data-v-70334359>什么是事务？</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#事务的acid" class="sidebar-link reco-side-事务的acid" data-v-70334359>事务的ACID</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#事务相关方法" class="sidebar-link reco-side-事务相关方法" data-v-70334359>事务相关方法</a></li><li class="level-3" data-v-70334359><a href="/blogs/GO/go_mysql/go_mysql.html#事务示例" class="sidebar-link reco-side-事务示例" data-v-70334359>事务示例</a></li></ul></main> <!----></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div><!----><canvas id="vuepress-canvas-cursor"></canvas></div></div>
    <script src="/assets/js/app.7029ddab.js" defer></script><script src="/assets/js/3.ebaa3085.js" defer></script><script src="/assets/js/1.8ce67e8c.js" defer></script><script src="/assets/js/40.56bda9a8.js" defer></script>
  </body>
</html>
